/**
* @ClassName: CategoryDaoImpl
* @Description: 
* @author YuYang
* @date 2013-6-5 上午12:46:30
*/
package com.demodis.dao.impl;

import java.util.ArrayList;
import java.util.List;

import com.demodis.dao.CategoryDaoI;
import com.demodis.domain.TblCategory;
import com.demodis.util.DBUtil;

public class CategoryDaoImpl extends BaseDao implements CategoryDaoI {

	@Override
	public boolean save(TblCategory t) {
		String sql = "INSERT INTO tbl_category(name,amount) VALUES(?, ?);";
		conn = DBUtil.getConnection();
		int i = 0;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, t.getName());
			ps.setInt(2, t.getAmount());
			i = ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(conn, ps, rs);
		}
		return i == 1 ? true : false;
	}

	@Override
	public boolean delete(TblCategory t) {
		String sql = "DELETE FROM tbl_category WHERE catId IN(" + t.getIds() + ");";
		int i = 0;
		try {
			conn = DBUtil.getConnection();

			ps = conn.prepareStatement(sql);
			i = ps.executeUpdate();

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			DBUtil.close(conn, ps, rs);
		}
		return i > 0 ? true : false;
	}

	@Override
	public boolean modify(TblCategory t) {
		String sql = "UPDATE tbl_category SET name = ?, amount = ? WHERE catId = ?;";
		int i = 0;
		try {
			conn = DBUtil.getConnection();
			ps = conn.prepareStatement(sql);

			ps.setString(1, t.getName());
			ps.setInt(2, t.getAmount());
			ps.setInt(3, t.getCatId());

			i = ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(conn, ps, rs);
		}
		return i == 1 ? true : false;
	}

	@Override
	public List<TblCategory> get() {
		String sql = "select * from tbl_category;";
		List<TblCategory> list = new ArrayList<TblCategory>();
		try {
			conn = DBUtil.getConnection();
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while (rs.next()) {
				TblCategory c = new TblCategory();
				c.setCatId(rs.getInt("catId"));
				c.setName(rs.getString("name"));
				c.setAmount(rs.getInt("amount"));
				list.add(c);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(conn, ps, rs);
		}
		return list;
	}

}
